package com.moonciki.artadmin.web.commons.filter;

import com.moonciki.artadmin.core.tools.BodyRepeatReadRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.web.servlet.filter.OrderedFilter;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * body 重复读的问题
 */
@Slf4j
@WebFilter(urlPatterns = "/**")
@Component
public class BodyRepeatReadFilter implements OrderedFilter {

	@Override
	public int getOrder() {
		return 0;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		//只对body 传参做request 处理
		String contentType = request.getContentType();
		if (StringUtils.isNotEmpty(contentType) && contentType.contains(MediaType.APPLICATION_JSON_VALUE)) {
			request = new BodyRepeatReadRequest((HttpServletRequest) request);
		}
		chain.doFilter(request, response);
	}

}
